const mongoose = require('mongoose')
const db = 'mongodb://localhost/smile-vue'
const glob = require('glob')
const {resolve} = require('path')

// 初始化schema
exports.initSchemas = () => {
  // 这里的require不太明白
  glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require)
}

exports.connect = () => {
  let maxReconnectTimes = 0
  // 链接数据库
  mongoose.connect(db)
  return new Promise((resolve, reject) => {
    // 增加数据库监听事件
    mongoose.connection.on('disconnected', () => {
      console.log('###########数据库断开###########')
      if (maxReconnectTimes < 3) {
        maxReconnectTimes++
        mongoose.connect(db)
      } else {
        reject()
        throw new Error('数据库出现问题，程序无法搞定，请人为处理。。。')
      }
    })

    mongoose.connection.on('error', err => {
      console.log('###########数据库错误###########')
      if (maxReconnectTimes < 3) {
        maxReconnectTimes++
        mongoose.connect(db)
      } else {
        reject(err)
        throw new Error('数据库出现问题，程序无法搞定，请人为处理。。。')
      }
    })
    mongoose.connection.once('open', () => {
      console.log('###########数据库链接成功###########')
      resolve()
    })
  })
}
